<template>
  <div class="upload-file">
    <a-upload ref="fileUpload" :action="state.uploadFileUrl" :headers="state.headers" :show-upload-button="!props.onlyShow"
      :show-remove-button="false" :limit="props.limit" :show-file-list="false" :show-retry-button="false"
      @exceed-limit="handleExceed" @error="handleUploadError" @before-upload="handleBeforeUpload" @success="handleUploadSuccess">
    </a-upload>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import {getToken} from "@/utils/auth";
import mittBus from "@/utils/route-listener"
import {reactive, ref, onMounted, defineProps, defineEmits, nextTick, computed} from "vue";

let props = defineProps({
  limit : {type : Number, default: 10000},
  fileSize : {type : Number, default: 80},
  fileType : {type : Array, default: () => ["xls",'xlsx']},
  //isShowTip : {type : Boolean, default: true},
  onlyShow : {type : Boolean, default: false},
  entityId : {type : Number, default: 0},
  entityTypeId : {type : Number, default: 0},
})

const state = reactive({
  baseUrl: import.meta.env.VITE_API_BASE_URL,
  uploadFileUrl: import.meta.env.VITE_API_BASE_URL + "/common/upload", // 上传文件服务器地址
  headers: {
    ['X-Token'] : getToken(),
    entityTypeId: ''+props.entityTypeId,
    entityId: ''+props.entityId,
  },
})
const tips = computed( () =>{
  if(props.isShowTip && (props.fileType || props.fileSize)){
    return "大小不超过" + props.fileSize +"MB的文件，格式为" + props.fileType?.join("/") + "的文件"
  }else{
    return "";
  }
})

// 文件个数超出
const handleExceed = ()=>{
  Message.error(`上传文件数量不能超过 ${props.limit} 个!`)
}
// 上传失败
const handleUploadError = (fileItem)=>{
  Message.error("上传文件失败，请重试" )
}
// 上传前校检格式和大小
const handleBeforeUpload = (file)=>{
  if(props.fileType){
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      Message.error(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  if(props.fileSize){
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      Message.error(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  return true;
}
// 上传成功回调
const handleUploadSuccess = (fileItem)=>{
  const res = JSON.parse(fileItem.response)
  if (parseInt(res.code) === 200 && fileItem.status == 'done') {
    const {data} = res;
    if(data.fId){
      mittBus.emit('import_bus', {fId : data.fId}) //mitt响应事件
    }else{
      Message.error(res.msg || '上传未知错误');
    }
  }else{
    Message.error(res.msg || '上传未知错误');
  }
}
onMounted(()=>{

})
</script>

<style scoped>

</style>
